<template>
    <div class="questionBankHomeView"> 
        <!-- 推荐题库 -->
         <div class="artistic-text">
            <span style="font-size: 24px;">推荐题库</span>
         </div>
         <div class="Box">
            <div class="Box-card" v-for="titleCard in titleCards" :key="titleCard.id"  @click="handleSelect">
                <el-image style="width: 75px; height: 75px; margin-right: 10px;" :src="titleCard.url" />
                <div class="Box-card-text">
                    <h5>
                        {{ titleCard.title }}
                    </h5>
                    <el-popover
                        placement="top"
                        :width="220"
                        trigger="hover"
                        :content="titleCard.content"
                    >
                        <template #reference>
                            <span class="Box-text-ellipsis">
                                {{ titleCard.content }}
                            </span>
                        </template>
                    </el-popover>
                </div>
            </div>
        </div>
        <div class="bottom">
            <el-button type="success" :icon="Check" @click="handleTest">随机测验</el-button>
            <el-button type="primary" :icon="Edit" @click="handleAdm">题库管理</el-button>
        </div>
        <QuestionBankData/>
        <!-- 对话框 -->
        <el-dialog v-model="dialogVisible" :title="title" width="900" :before-close="handleClose">
            <el-form ref="ruleFormRef"  :model="ruleForm" :rules="rules" label-width="100px">
                
                <el-row gutter={20}> <!-- 用 el-row 包裹 el-col，设置列间距 -->
                    <el-col :span="11"> <!-- 左边的输入框 -->
                        <el-form-item label="选择题数" prop="multipleChoice">
                            <el-input v-model="ruleForm.multipleChoice"  placeholder="请输入随机出选择题数" type="number"/>
                             <!-- <input v-model="ruleForm.multipleChoice" placeholder="请输入随机出选择题数" type="number"></input> -->
                        </el-form-item>
                    </el-col>

                    <el-col :span="11"> <!-- 右边的输入框 -->
                        <el-form-item label="填空题" prop="gapFilling">
                            <el-input v-model="ruleForm.gapFilling" placeholder="请输入随机出填空题" type="number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row gutter={20}> <!-- 新的一行，分成左右两个输入框 -->
                    <el-col :span="11">
                        <el-form-item label="判断题" prop="trueOrFalse">
                            <el-input v-model="ruleForm.trueOrFalse"  placeholder="请输入随机出判断题" type="number"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="11">
                        <el-form-item label="简答题" prop="shortAnswer">
                            <el-input v-model="ruleForm.shortAnswer" placeholder="请输入随机出简答题" type="number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row gutter={20}> <!-- 另一行，用 el-row 继续分配输入框 -->
                    <el-col :span="11">
                        <el-form-item label="难度" prop="difficulty">
                        <el-select v-model="ruleForm.difficulty" placeholder="请选择出题难度">
                            <el-option v-for="item in difficults" :key="item" :label="item" :value="item" />
                        </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="11">
                        <el-form-item label="设置知识点" prop="knowledge">
                        <el-select v-model="ruleForm.knowledge" placeholder="请选择知识点">
                            <el-option v-for="item in knowledges" :key="item" :label="item" :value="item" />
                        </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item class="button-group">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
 
<script lang="ts">
import TagBox from '@/components/course/CourTypeLabelBox.vue';
import QuestionBankData from '@/views/questionBank/替代的组件/QuestionBankData.vue';
import { Check, Edit,} from '@element-plus/icons-vue'
import { ref ,reactive } from 'vue'
import { ElMessageBox, FormInstance, FormRules, ImageProps} from 'element-plus'
import { useRouter } from 'vue-router';

    export default {
        name: 'questionBankHomeView',
        components:{
            TagBox,
            QuestionBankData
        }
    }
</script>

<script setup lang="ts">
    // 定义表单数据类型
    interface  RuleForm {
        multipleChoice: number | null
        gapFilling: number  | null
        trueOrFalse: number  | null
        shortAnswer: number  | null
        difficulty: string
        knowledge: string
    }
    // 暴露路由
    const router = useRouter();
    // 暴露标题
    const title = ref('随机测验')
    // 对话框是否可见
    const ruleFormRef = ref<FormInstance>()
    // 图片路径
    // const url ='https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
    const titleCards = reactive(
        [
            {
                id: '1',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/top-interview-150/cover',
                title: '面试经典150题',
                content: '最经典50题掌握面试技巧，让你快速通过面试'
            },
            {
                id: '2',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/dynamic-programming/cover',
                title: '动态规划(基础版)',
                content: '更细的知识点拆分，让入门更简单'
                },
            {
                id: '3',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/top-100-liked/cover',
                title: 'java入门题',
                content: '小白速度入门'
            },
            {
                id: '4',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/sql-premium-50/cover',
                title: '高频SQL题',
                content: '对应高阶数据库'
            },
            {
                id: '5',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/primers-list/cover',
                title: '[新]动计划·编程入门',
                content: '编程初学者的力扣适应手册'
            },
            {
                id: '6',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/special-interview-119/cover',
                title: '排序算法',
                content: '锻炼思维、思辨能力，让排序一眼望穿'
            },
            {
                id: '7',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/30-days-of-javascript/cover',
                title: '30天JavaScript挑战',
                content: '30天30题入门JavaScript'
            },
            {
                id: '8',
                url: 'https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/mi-2023-fall-sprint/cover',
                title: '小米秋招真题笔记',
                content: '趁年轻，做点更真的题'
            },
        ]
        
    )
    // form 提交表单的数据
    const ruleForm = reactive<RuleForm>({
        multipleChoice: null,  // 选择题
        gapFilling: null,    // 填空题
        trueOrFalse: null,   // 判断题
        shortAnswer: null,   // 简答题
        difficulty: '',   // 难度
        knowledge: ''     // 知识点
    })
    // 校验规则（不能为负数）
    const validateNonNegative = (rule: any, value: string, callback: any) => {
    // 确保 value 是一个有效的数字并且不小于 0
    const numValue = Number(value);
    if (value !== '' && (isNaN(numValue) || numValue <0 )) {
        callback(new Error('输入值必须是一个非负数'));
    } else {
        callback();
    }
}

    //表单验证规则
    const rules = reactive<FormRules<RuleForm>>({
        multipleChoice: [  
            { min: 1, max: 2, message: '长度在1-2之间', trigger: 'blur' },
            { validator: validateNonNegative, trigger: 'blur' }
        ],
        gapFilling: [
            { min: 1, max: 2, message: '长度在1-2之间', trigger: 'blur' },
            { validator: validateNonNegative, trigger: 'blur' }
        ],
        trueOrFalse: [
            { min: 1, max: 2, message: '长度在1-2之间', trigger: 'blur' },
            { validator: validateNonNegative, trigger: 'blur' }
        ],
        shortAnswer: [
            { min: 1, max: 2, message: '长度在1-2之间', trigger: 'blur' },
            { validator: validateNonNegative, trigger: 'blur' }
        ],
        difficulty: [
            { required: true, message: '请选择出题难度', trigger: 'blur' }
        ],
        knowledge: [
            { required: true, message: '请选择知识点', trigger: 'blur' }
        ]
    })

    // 难度系数
    const difficults= ref(['简单','中等','困难'])
    // 知识点系数
    const knowledges= ref(['Java','JavaScript','HTML','CSS','MySQL','Spring','SpringBoot','MyBatis','Redis','Linux','Maven','Git','其他'])

    // 暴露按钮图标
    defineExpose({  
        Edit,
        Check
    });
    // 对话框是否可见
    const dialogVisible = ref(false)
    //关闭/打开对话框的函数
    const handleClose = (done: () => void) => {
        ElMessageBox.confirm('你确认关闭对话框吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'custom-message-box' // 添加自定义类名
        }).then(() => {
            done();
            resetForm(ruleFormRef.value); // 传递 ruleFormRef
        }).catch(() => {
            // 取消操作
        });
    };

    // 处理获取标签的逻辑
    const handleGetTags = (tags: number[]) => {
        console.log('选择的标签:', tags);
    }

    // 题库管理按钮
    const handleAdm = () => {
        router.push({ name: 'questionBankManagement' });
    }
    const handleSelect = () => {
        router.push({ name: 'questionBankRandomQuiz' });
    }
    // 随机测验按钮
    const handleTest = () => {
        dialogVisible.value = true
    }
    // 提交表单
    const submitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) return

        await formEl.validate((valid, fields) => {
            if (valid) {
                // console.log('submit!')
                console.log(ruleForm.multipleChoice)
                console.log(ruleForm.knowledge)
                console.log(typeof ruleForm.multipleChoice, ruleForm.multipleChoice); // 检查数据类型
                console.log(typeof ruleForm.knowledge, ruleForm.knowledge); // 检查数据类型
                router.push(
                    { 
                        name: 'questionBankRandomQuiz' ,
                        // console.log(ruleForm)
                        params: {
                            multipleChoice: ruleForm.multipleChoice || 0,
                            gapFilling: ruleForm.gapFilling || 0,
                            trueOrFalse: ruleForm.trueOrFalse || 0,
                            shortAnswer: ruleForm.shortAnswer || 0,
                            difficulty: ruleForm.difficulty,
                            knowledge: ruleForm.knowledge
                        }
                    }
                )
                console.log(ruleForm)
                console.log(router)
                resetForm(formEl)
                dialogVisible.value = false // 关闭对话框
            } else {
                console.log('error submit!', fields)
            }
        })
    }
    // 重置表单
    const resetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
        dialogVisible.value = false // 关闭对话框
    }


</script>


<style scoped>
.questionBankHomeView{
    width: var(--width);
    height: 100%;
    margin-top: 20px;
    border-radius: 5px;
    margin-right: 10px;
}
/* 第一行（字体题库和题库管理按钮） */
.header {
    display: flex; /* 使用 Flexbox */
    justify-content: space-between; /* 将内容分布到两边 */
    align-items: center; /* 垂直居中对齐 */
}
/* 题库字体 */
h2{
    width: 100px;
    margin: 0; /* 去掉默认的 margin */
    font-size: 26px
}
/* 推荐题库字体 */
.artistic-text {
   margin-bottom: 10px;
  font-family: 'Pacifico', cursive; /* 使用自定义字体 */
  color:  #00BFFF;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* 添加阴影 */
  transform: skew(-10deg); /* 文本倾斜 */
  display: inline-block; /* 使transform生效 */
}
/* 卡片大盒子 */
.Box{
    width: 1300px; /* 设置为两列的总宽度，卡片宽度300px + 间距20px */
    display: flex;
    flex-wrap: wrap; /* 允许换行 */
    /* justify-content: center; */
    gap: 31px; /* 卡片之间的间距 */
}
/* 卡片 */
.Box-card{
    width: 300px; /* 保持单个卡片宽度 */
    height: 90px;
    display: flex;
    align-items: center;
    background: white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    padding: 10px;
    overflow: hidden;
    transition: box-shadow 0.3s ease; /* 添加过渡效果 */
}

/* 获取焦点时的样式 */
.Box-card:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3); /* 增加阴影的可见度 */
    cursor: pointer; /* 鼠标悬停时显示手形光标（如果需要） */
}

/* 卡片文字 */
.Box-card-text{
    flex: 1; 
    overflow: hidden;
}

h5{
    margin: 0; 
    font-size: 15px; 
    font-weight: bold; 
    line-height: 1.2;
}
/* 文本溢出显示省略号 */
.Box-text-ellipsis{
    font-size: 12px; 
    color: #666; 
    white-space: nowrap; 
    overflow: hidden; 
    text-overflow: ellipsis; 
    display: block; 
    margin-top: 6px;
}

/* 题库管理按钮 */
.bottom {
    display: flex;
    justify-content: flex-end; /* 将按钮对齐到右边 */
    margin-top: 20px;
}
/* 标签框 */
.TagBox{
    margin-top: 20px;
}
/* 表单标签 */
.el-form-item {
  width: 400px !important; /* 设置标签宽度 */
  margin-left: 80px;
}
/* 输入框宽度 */
.el-input{
    width: 200px;
}
/* 下拉框宽度 */
.el-select{
    width: 200px;
}
/* 对话框按钮组 */
.button-group{
    margin-left: 270px;
}

::v-deep  .el-dialog{
    margin-top: 350px;
}
/* ::v-deep .el-message-box {
    margin-top: -150px ; 
} */

</style>